<!--
 * @Author: zegobuilder zegobuilder@zego.im
 * @Date: 2022-11-01 19:50:11
 * @LastEditors: zegobuilder zegobuilder@zego.im
 * @LastEditTime: 2023-02-27 17:47:09

-->
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>Zego Express Video Call</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <!-- <script src="./dist/ZegoExpressWebRTC.js"></script> -->
  <script src="./js/ZegoExpressWebRTC-2.17.0.js"></script>
  <link rel="stylesheet" href="css/styles.css" />
</head>

<body>
  <h1>Zego RTC Video Call</h1>
  <div class="video-wrapper">

    <button onclick="login()">登录房间</button>
    <input type="text" id="roomid" placeholder="请输出房间号">
    <button onclick="startPush()">推摄像头流</button>
    <button onclick="startPushScreen()">推屏幕共享流</button>
    <button onclick="enableCamera()">开关摄像头</button>
    <button onclick="enableMic()">开关麦克风</button>
    <button onclick="logoutRoom()">退出房间</button>
    <br />
    <hr />
    <div>
      <button onclick="switchConstraints()">修改推流参数</button>
      宽<input type="text" id="width">
      高<input type="text" id="height">
      码率<input type="text" id="bitrate">
      帧率<input type="text" id="frameRate">
    </div>

    <h4>Local video</h4>
    <div id="local-video" style="height: auto;"></div>
    <div class="remoteVideo"></video>
      <dic id="remoteVideo">
    </div>
    <div id="rv"></div>
  </div>
  <div id="information"></div>
</body>
<script>
  //初始化信息
  let appID = 1739272706
  let server = 'wss://webliveroom-test.zego.im/ws'

  let userID = 'alagong' + new Date().getTime(); // userID 用户自己设置，必须保证全局唯一
  let userName = '阿拉贡' + new Date().getTime() // userName 用户自己设置，没有唯一性要求
  let roomID = '' // roomID 用户自己设置，必须保证全局唯一
  let localStream = null
  let localAuidoStream = null
  let localVideoStream = null
  let mutedCamera = false
  let useLocalStreamList = [];
  let remoteStream = null;
  let cameraStream;
  let screenStream;
  let accessToken = '';
  let cameraStreamID, screenStreamID;
  // 初始化实例
  const zg = new ZegoExpressEngine(appID, server)

  zg.setDebugVerbose(false);
  zg.on('roomStreamUpdate', async (roomID, updateType, streamList, extendedData) => {
    console.log('roomStreamUpdate 1 roomID ', roomID, streamList, extendedData);
    if (updateType == 'ADD') {
      for (let i = 0; i < streamList.length; i++) {
        console.info(streamList[i].streamID + ' was added');
        let remoteStream;
        let playOption={
          audio:true,
          video:false
        };


        zg.startPlayingStream(streamList[i].streamID, playOption).then(stream => {
          remoteStream = stream;
          useLocalStreamList.push(streamList[i]);

          let remoteView = zg.createRemoteStreamView(remoteStream);
          remoteView.play("remoteVideo", {
            objectFit: "cover",
            muted: false,
          })
          // video.muted = false;
        }).catch(err => {
          console.error('err', err);
        });

      }
    } else if (updateType == 'DELETE') {
      for (let k = 0; k < useLocalStreamList.length; k++) {
        for (let j = 0; j < streamList.length; j++) {
          if (useLocalStreamList[k].streamID === streamList[j].streamID) {
            try {
              zg.stopPlayingStream(useLocalStreamList[k].streamID);
            } catch (error) {
              console.error(error);
            }
            useLocalStreamList.splice(k--, 1);
            break;
          }
        }
      }
    }
  });

  async function login() {
    roomID = document.getElementById("roomid").value ? document.getElementById("roomid").value : alert("请输入房间号");
    fetch(
        `https://wsliveroom-alpha.zego.im:8282/token?app_id=${appID}&id_name=${userID}`
      )
      .then((rsp) => rsp.text())
      .then((token) => {
        accessToken = token
        zg.loginRoom(
            roomID,
            accessToken, {
              userID,
              userName
            }, {
              userUpdate: true
            }
          )
          .then((rsp) => {
            loginSuc = true;
          })
          .catch((err) => console.error('[yyyy]', err))
      })
  }

  async function startPush() {
    const config = {
      camera:{
        videoQuality: 1,
        audio: true,
        video: true,
      },
    };
    cameraStream = await zg.createStream(config);
    let localView = zg.createLocalStreamView(cameraStream);
    localView.play("local-video", {
      muted: true,
      objectFit: "cover",
    })
    cameraStreamID = "camera_" + new Date().getTime();
    zg.startPublishingStream(cameraStreamID, cameraStream,{videoCodec:"VP8"})
  }
  async function startPushScreen() {
    const config = {
      screen: {
        audio: false,
        video: true,
      },
    };
    screenStream = await zg.createStream(config);
    screenStreamID = "screen_" + new Date().getTime();
    zg.startPublishingStream(screenStreamID, screenStream,{videoCodec:"VP8"})
  }

  function switchConstraints() {
    const constraints = {};
    const w = document.getElementById("width").value ? parseInt(document.getElementById("width").value) : 0;
    const h = document.getElementById("height").value ? parseInt(document.getElementById("height").value) : 0;
    const f = document.getElementById("frameRate").value ? parseInt(document.getElementById("frameRate").value) : 0;
    const b = document.getElementById("bitrate").value ? parseInt(document.getElementById("bitrate").value) : 0;

    w && Object.assign(constraints, {
      width: w
    });
    h && Object.assign(constraints, {
      height: h
    });
    f && Object.assign(constraints, {
      frameRate: f
    });
    b && Object.assign(constraints, {
      maxBitrate: b
    });

    zg.setVideoConfig(cameraStream, constraints).then(
      () => {
        console.warn('change constraints success');
      },
      err => {
        console.error(err);
      },
    );
  }
  //开关摄像头
  function enableCamera() {
    mutedCamera = !mutedCamera
    zg.mutePublishStreamVideo(cameraStream, mutedCamera)
  }
  //开关麦克风
  function enableMic() {
    mutedCamera = !mutedCamera
    zg.mutePublishStreamAudio(cameraStream, mutedCamera)
  }

  function logoutRoom() {
    cameraStreamID && zg.stopPublishingStream(cameraStreamID);
    screenStreamID && zg.stopPublishingStream(screenStreamID);
    cameraStream && zg.destroyStream(cameraStream);
    screenStream && zg.destroyStream(screenStream);
    zg.logoutRoom(roomID)
  }
</script>

</html>